package com.xmg.leetCode;

/**
 * 编写一个函数来查找字符串数组中的最长公共前缀。
 *
 * 如果不存在公共前缀，返回空字符串 ""。
 *
 * 示例 1：
 *
 * 输入：strs = ["flower","flow","flight"]
 * 输出："fl"
 * 示例 2：
 *
 * 输入：strs = ["dog","racecar","car"]
 * 输出：""
 * 解释：输入不存在公共前缀。
 *
 * 思路：两两比较，每次拿前两个得出的前缀和第三个比较
 */
public class No14 {
    public static void main(String[] args) {
        String[] strs = {"flower","flow","flight"};
        System.out.println(Solution14.longestCommonPrefix(strs));
    }
}

class Solution14 {
    public static String longestCommonPrefix(String[] strs) {
        if (strs.length==0){
            return "";
        }
        if(strs.length==1){
            return strs[0];
        }
        String pre = strs[0];
        for (int i = 1; i < strs.length; i++) {
            pre = getLongStr(pre,strs[i]);
            if(pre==""){
                return "";
            }
        }
        return pre;
    }

    public static String getLongStr(String str1,String str2){
        StringBuilder str = new StringBuilder();
        int index = 0;
        int len = Math.min(str1.length(),str2.length());
        while (index<len && str1.charAt(index) == str2.charAt(index)){

            str.append(str1.charAt(index));
            index++;
        }
        return str.toString();
    }

    public static String longestCommonPrefix2(String[] strs) {
        if (strs.length == 0) return "";
        String result = strs[0];
        if (strs.length == 1) return strs[0];
        for (int i = 0; i < strs.length; i++) {
            if (!strs[i].startsWith(result)) {
                result = result.substring(0, result.length() - 1);
                i--;
            }
        }

        return result;
    }
}